﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Manager;
using System.Data;
using Model;
using ExtAspNet;
using Manager.Helper;
namespace HealthSystem
{
    public partial class ResultFileUpload : BasePage
    {
        HW_SchoolManager manager = new HW_SchoolManager();
        ServerUploadLogManager uploadLogManager = new ServerUploadLogManager();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Initialize();
                BindGrid();
                //fileGridBind();
            }
        }
        public void BindGrid()
        {
            int count = 0;
            DataTable list = new DataTable();
            Gird1.IsDatabasePaging = true;
            if (CustomerProfile.RoleId.ToString().StartsWith("1"))
            {
                if (actionbt.Text == "search")
                {
                    list = manager.Search(Gird1.PageIndex, Gird1.PageSize, out count, CustomerProfile.DistrictId, searchbox.Text);
                }
                else
                {
                    if (!string.IsNullOrEmpty(districtid.Text))
                    {
                        list = manager.GetSchoolDetail(Gird1.PageIndex, Gird1.PageSize, out count, districtid.Text);
                    }
                    else
                    {
                        list = manager.GetSchoolDetail(Gird1.PageIndex, Gird1.PageSize, out count, CustomerProfile.DistrictId);
                    }
                    for (int i = 0; i < list.Rows.Count; i++)
                    {
                        list.Rows[i]["permit"] = list.Rows[i]["permit"] is DBNull ? false : list.Rows[i]["permit"];
                    }
                }
            }
            if (CustomerProfile.RoleId == 2000)
            {
                list = manager.GetSchoolByOrgCode(Gird1.PageIndex, Gird1.PageSize, out count, CustomerProfile.OrgUser.OrgCode);
            }
            if (CustomerProfile.RoleId == 3000)
            {
                list = manager.GetSchoolBySchoolCode(Gird1.PageIndex, Gird1.PageSize, out count, CustomerProfile.SchoolUser.SchoollCode);
            }
            Gird1.RecordCount = count;
            this.Gird1.DataSource = list;
            this.Gird1.DataBind();
        }
        private void Search()
        {

            if (string.IsNullOrEmpty(searchbox.Text))
            {
                ExtAspNet.Alert.Show("请输入查询条件");
                return;
            }
            int count = 0;
            DataTable list = manager.Search(Gird1.PageIndex, Gird1.PageSize, out count, CustomerProfile.DistrictId, searchbox.Text);
            for (int i = 0; i < list.Rows.Count; i++)
            {
                list.Rows[i]["permit"] = list.Rows[i]["permit"] is DBNull ? false : list.Rows[i]["permit"];
            }
            Gird1.IsDatabasePaging = false;
            this.Gird1.DataSource = list;
            this.Gird1.DataBind();
            actionbt.Text = "search";
        }
        protected void Search_Clik(object sender, EventArgs e)
        {
            Gird1.PageIndex = 0;
            Search();
            actionbt.Text = "search";
        }
        protected void PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            int pageindex = e.NewPageIndex;
            Gird1.PageIndex = pageindex;
            BindGrid();
        }
        protected void Upload_Click(object sender, EventArgs e)
        {
            string FileName = this.AttachFile.FileName;//获取上传文件的全路径
            if (Gird1.SelectedRowIndexArray.Length==0)
            {
                Alert.Show("请先选择要上传记录的学校");
                return;
            }
            string schoolCode = Gird1.Rows[Gird1.SelectedRowIndex].DataKeys[0].ToString();
            string schoolName = Gird1.Rows[Gird1.SelectedRowIndex].DataKeys[1].ToString();
            string ExtenName = System.IO.Path.GetExtension(FileName);//获取扩展名
            if (ExtenName.ToUpper() != ".XLS" && ExtenName.ToUpper() != ".XLSX")
            {
                Alert.Show("只能上传EXCEL文件");
                return;
            }
            string path = System.Configuration.ConfigurationManager.AppSettings["resultpath"].ToString()+"\\"+DateTime.Now.Year.ToString();
            string fullPath = path + "\\" + schoolCode + ExtenName;
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            if (System.IO.File.Exists(fullPath))
            {
                ExtAspNet.Alert.Show("该学校体检结果在"+DateTime.Now.Year.ToString()+"年已经有过上传记录，请先处理");
                return;
            }
            string SaveFileName = System.IO.Path.Combine(path, schoolCode + ExtenName);//合并两个路径为上传到服务器上的全路径

            if (this.AttachFile.ContentLength > 0)
            {

                try
                {

                    //检查是否正确格式excel
                    ServerExcel serverExcel = new ServerExcel(schoolCode, schoolName, SaveFileName);
                    //保存excel
                    this.AttachFile.MoveTo(SaveFileName, Brettle.Web.NeatUpload.MoveToOptions.Overwrite);
                    //导入excel件
                    DataSet ds= serverExcel.ImportExcel();
                    //测试excel文件
                    string testResult = "";
                    //string testResult= serverExcel.TestData(ds,schoolCode,schoolName);
                    if (!string.IsNullOrEmpty(testResult))
                    {
                        Alert.Show(testResult);
                        if (System.IO.File.Exists(fullPath))
                        {
                            try
                            {
                                System.IO.File.Delete(fullPath);
                            }
                            catch (Exception exc)
                            {
                                Alert.Show(exc.Message);
                            }
                        }
                    }
                    else
                    {
                        ServerUploadLog log = new ServerUploadLog()
                        {
                            LogSchool = schoolCode,
                            LogSchoolName = schoolName,
                            LogDate = DateTime.Now,
                            FilePath = SaveFileName,
                            FileType = ExtenName,
                            State = "X",
                            UploadUser=CustomerProfile.UserName,
                        };
                        if (CustomerProfile.RoleId == 1001)
                        {
                            log.UploadUserName = CustomerProfile.AdminUser.CNName;
                        }
                        if(CustomerProfile.RoleId==2000)
                        {
                            log.UploadUserName = CustomerProfile.OrgUser.hw_Org.OrgName;
                        }
                        uploadLogManager.Add(log);
                        
                        Alert.Show("您的数据已经保存到服务器,我们会尽快处理");
                        //fileGridBind();
                    }
                }

                catch (Exception ex)
                {
                    Alert.Show(ex.Message);
                    if (System.IO.File.Exists(fullPath))
                    {
                        try
                        {
                            System.IO.File.Delete(fullPath);
                        }
                        catch(Exception exc)
                        {
                            Alert.Show(exc.Message);
                        }
                    }

                }

            }

        }
        //public void fileGridBind()
        //{
        //    int count = 0;
        //    fileGrid.DataSource=uploadLogManager.GetLog(fileGrid.PageIndex, fileGrid.PageSize, out count);
        //    fileGrid.RecordCount = count;
        //    fileGrid.DataBind();

        //}
        public void Initialize()
        {
            if (!CustomerProfile.RoleId.ToString().StartsWith("1"))
            {
                label1.Visible = false;
                name.Visible = false;
                searchbox.Visible = false;
            }
            //if (CustomerProfile.RoleId == 2000)
            //{
            //    ExtAspNet.LinkButtonField link = new LinkButtonField();
            //    link.HeaderText = "验证文件下载";
            //    link.Text = "验证文件下载";
            //    link.CommandName = "download";
            //    Gird1.Columns.Add(link);
            //}
        }
    }
}